<?php
defined('PT_ACCESS') or die('No direct access');

abstract class ActionController extends Controller{
	protected $name;
	protected $viewData = array();
	protected $smarty;
	protected $displayView = true;

	public function setName($name){
		$this->name = $name;
	}

	public function getName(){
		return $this->name;
	}

	public function dispatchAction($action, $switch = ''){
		$actionMethod = lcfirst($action) . 'Action';
		if (!method_exists($this, $actionMethod)){
			$this->forward('error', 'notFound');
			exit();
		}
		$this->$actionMethod();
		if ($this->displayView)
			$this->displayView($action, $switch);
	}

	public function displayView($action, $switch = ''){
		$this->loadSmarty();

		require DIR_LANGUAGE . LANGUAGE . '/' . LANGUAGE . '.php';
		$this->viewData = array_merge($lang, $this->viewData);

		//Create variables for the template
		foreach ($this->viewData as $key=>$value){
			$this->smarty->assign($key, $value);
		}

		if ($switch == ADMIN){
			// Da dang nhap admin
			$this->smarty->assign('adminUrl', '/' . ADMIN . '/');
			$this->smarty->assign('httpRequest', HTTP_ADMIN_REQUEST);
			$this->smarty->assign('tempDir', DIR_ADMIN_TEMPLATE);
			$this->smarty->display(DIR_ADMIN_TEMPLATE . $this->getName() . '/' . $action . '.tpl');
		}elseif ($switch == 'adlogin'){
			// Neu chua dang nhap admin thi chuyen huong toi trang dang nhap admin
			$this->smarty->assign('httpRequest', HTTP_ADMIN_REQUEST);
			$this->smarty->assign('tempDir', DIR_ADMIN_TEMPLATE);
			$this->smarty->display(DIR_ADMIN_TEMPLATE . 'login/' . $action . '.tpl');
		}elseif ($switch == 'login'){
			// Member login form
			$this->smarty->assign('httpRequest', HTTP_REQUEST);
			$this->smarty->assign('tempDir', DIR_TEMPLATE . THEME);
			$this->smarty->display(DIR_TEMPLATE . THEME . 'login/' . $action . '.tpl');
		}else{
			// at Home
			$this->smarty->assign('httpRequest', HTTP_REQUEST);
			$this->smarty->assign('tempDir', DIR_TEMPLATE . THEME);
			$this->smarty->display(DIR_TEMPLATE . THEME . $this->getName() . '/' . $action . '.tpl');
		}
	}

	protected function loadSmarty(){
		$this->smarty = new Smarty();
		$this->smarty->debugging = (APP_ENV == 'dev') ? true : false;
		$this->smarty->caching = SMARTY_CACHE;
		$this->smarty->cache_lifetime = SMARTY_CACHE_LIFE;
		$this->smarty->force_compile = true;
		$this->smarty->allow_php_tag = true;
		$this->smarty->compile_check = true;
		$this->smarty->allow_php_templates = true;

		$this->smarty->setTemplateDir(DIR_VIEW . 'templates');
		$this->smarty->setCompileDir(APP_ROOT . 'tmp/templates_c');
		$this->smarty->setCacheDir(APP_ROOT . 'tmp/cache');
		$this->smarty->setConfigDir(APP_ROOT . 'tmp/configs');

		//Register Smarty Plugins
//		$this->smarty->registerPlugin("function", "url", "url");
//		$this->smarty->registerPlugin("function", "action", "action");
	}
}
